/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.unice.miage.projetjava.managers;

import fr.unice.miage.projetjava.entities.Users;
import fr.unice.miage.projetjava.entities.LigneDeCommande;
import fr.unice.miage.projetjava.*;
import fr.unice.miage.projetjava.entities.Commande;
import java.util.Collection;
import java.util.Date;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean gerant Commande
 * @author arnaud
 */
@Stateful
public class GestionnaireDeCommandeBean implements GestionnaireDeCommandeLocal
{
    @PersistenceContext
    private EntityManager em;
    
    // Add business logic below. (Right-click in editor and choose
    // "EJB Methods > Add Business Method" or "Web Service > Add Operation")

    public Commande newCommande(Users user, Date date)
    {
        Commande commande = new Commande();
        commande.setOwner(user);
        commande.setDateDeCommande(date);
        em.persist(commande);
        return commande;
    }

    public void deleteCommande(int id)
    {
        Commande commande = em.find(Commande.class, id);
        em.remove(commande);
    }
    
    public Collection<Commande> listeDeCommande(Users user)
    {
        Query query = em.createQuery("SELECT c FROM Commande c WHERE c.owner='"+user+"'");
        return query.getResultList();
    }
    
    public void ajouterLigneDeCommande(Commande command, LigneDeCommande lc)
    {
        Commande commande = em.find(Commande.class, command);
        LigneDeCommande ldc = em.find(LigneDeCommande.class, lc);
        commande.ajouterLigneDeCommande(ldc);
    }
    
    public void retirerLigneDeCommande(Commande command, LigneDeCommande lc)
    {
        Commande commande = em.find(Commande.class, command);
        LigneDeCommande ldc = em.find(LigneDeCommande.class, lc);
        commande.retirerLigneDeCommande(ldc);
    }

    public Commande getCommande(int id)
    {
        Commande commande = em.find(Commande.class, id);
        return commande;
    }

    public void persist(Object object)
    {
        em.persist(object);
    }

}
